package com.yc.network;

import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 1. 当控制台输入: 发送==>c:/a.txt, 开始发送文件
 * 2. 将文件大小, 文件告诉接收端:   文件:a.txt:456
 */

public class QQClient {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8888);
        System.out.println("连接服务器成功!");

        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        Scanner scanner = new Scanner(System.in);

        new Thread() {
            public void run() {
                while (true) {
                    System.out.print("请输入:");
                    String msg = scanner.nextLine();  // 阻塞点
                    if(msg.startsWith("发送==>")){
                        sendFile(out,msg);
                    }
                    try {
                        out.write(msg.getBytes(StandardCharsets.UTF_8));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread() {
            public void run() {
                while (true) {
                    byte[] buffer = new byte[1024];
                    int count = 0;  // 阻塞点
                    try {
                        count = in.read(buffer);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("服务器说:" + new String(buffer, 0, count));
                }
            }
        }.start();
    }


    public static void sendFile(OutputStream out, String msg) {
        String[] items = msg.split("==>");
        String filepath = items[1];
        String filename = items[1].substring(items[1].lastIndexOf("/"));
        File file = new File(filepath);
        long size = file.length();
        String sendMsg = "文件:" + filename + ":" + size;
        // JDK 1.8 新语法, 不用关闭流
        try (FileInputStream fis = new FileInputStream(file)) {
            out.write(sendMsg.getBytes(StandardCharsets.UTF_8));
            byte[] bytes = new byte[1024];
            int count;
            while ((count = fis.read(bytes)) > -1) {
                out.write(bytes, 0, count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
